
/**
 * 描述 当前库可以运行在 浏览器 环境和 Node 环境
 * 时间：2022-04-11
 * 作者：自夏
 */


// 小于9的数字补齐 为09 
const PaddingBytes = (n: number) => (n <= 9 ? `0${n}` : n);

let Dates = new Date(),

  Year = Dates.getFullYear(), // 年
  Month = Dates.getMonth() + 1, // 月
  strDate = PaddingBytes(Dates.getDate()),// 日
  hour = PaddingBytes(Dates.getHours()), // 时
  minute = PaddingBytes(Dates.getMinutes()), // 分
  second = PaddingBytes(Dates.getSeconds()), // 秒
  time = Dates.getTime(), // 时间戳
  Day = Dates.getDay() // 周几

setTimeout(() => {
  Dates = new Date()
  Year = Dates.getFullYear(), // 年
    Month = Dates.getMonth() + 1, // 月
    strDate = PaddingBytes(Dates.getDate()),// 日
    hour = PaddingBytes(Dates.getHours()), // 时
    minute = PaddingBytes(Dates.getMinutes()), // 分
    second = PaddingBytes(Dates.getSeconds()), // 秒
    time = Dates.getTime(), // 时间戳
    Day = Dates.getDay() // 周几
}, 1000)

/**
* 获取周一到周
*/
const mondayToWeekend = () => {
  const oneDayTime = 24 * 60 * 60 * 1000,
    MondayTime = time - (Day - 1) * oneDayTime, // 显示周一
    SundayTime = time + (7 - Day) * oneDayTime;//显示周日

  const d = new Date(MondayTime),
    begintime = `${d.getFullYear()}-${PaddingBytes(d.getMonth() + 1)}-${PaddingBytes(d.getDate())}`,
    d1 = new Date(SundayTime),
    weekend = `${d1.getFullYear()}-${PaddingBytes(d1.getMonth() + 1)}-${PaddingBytes(d1.getDate())}`;

  return {
    monday: begintime,
    weekend: weekend
  };

};

export default {

  /**
   *@describe 获取系统当前时间  年月日时分秒
   @param {用于分割当前时间} slice 
   @optional {'date','tiem'}
   * @return 2021-10-11 14:58:02
   */
  getData(slice: string | null) {
    let currentdate = `${Year}-${Month}-${strDate}`,
      current = `${hour}:${minute}:${second}`;
    return slice === 'date' ? currentdate : slice === 'tiem' ? current : `${currentdate} ${current}`;
  },

  /**
   * 传入时间格式为yyyyMMddhhmmss 返回格式化时间为yyyy-MM-DD HH:mm:ss格式
   * @param {string and number} time 
   *  * @param {string} Division 
   * @returns string
   */
  formatTime(time: string | undefined, Division = "-") {
    if (time == undefined) {
      throw new Error('time 参数必传')
    }

    time = String(time);
    return (
      time.slice(0, 4) +
      `${Division}` +
      time.slice(4, 6) +
      `${Division}` +
      time.slice(6, 8) +
      " " +
      time.slice(8, 10) +
      ":" +
      time.slice(10, 12) +
      ":" +
      time.slice(12, 14)
    );
  },

  /**
   * 给秒 返回 小时-分钟-秒
   * @param {number} value 
   * @returns 
   */
  secondsConversion(value: string) {
    let result = parseInt(value);
    let h =
      Math.floor(result / 3600) < 10 ?
        "0" + Math.floor(result / 3600) :
        Math.floor(result / 3600);
    let m =
      Math.floor((result / 60) % 60) < 10 ?
        "0" + Math.floor((result / 60) % 60) :
        Math.floor((result / 60) % 60);
    let s =
      Math.floor(result % 60) < 10 ?
        "0" + Math.floor(result % 60) :
        Math.floor(result % 60);

    let res = "";
    if (h !== "00") res += `${h}h`;
    if (m !== "00") res += `${m}min`;
    res += `${s}s`;
    return res;
  },

  // 给秒 返回 小时和秒
  s_to_hs(s: any) {
    //计算分钟
    //算法：将秒数除以60，然后下舍入，既得到分钟数
    var h: any;
    h = Math.floor(s / 60);
    //计算秒
    //算法：取得秒%60的余数，既得到秒数
    s = s % 60;
    //将变量转换为字符串
    h += "";
    s += "";
    //如果只有一位数，前面增加一个0
    h = h.length == 1 ? "0" + h : h;
    s = s.length == 1 ? "0" + s : s;
    return h + ":" + s;
  },

  /**
   * 比较二个时间相差
   * @param startTime 对比开始时间
   * @param endTime    对比结束时间
   * @param diffType 返回对比类型参数  second 秒   minute分  hour 小时  day 天
   * @returns {number} 返回 设置的 秒 分 小时 天
   * @constructor
   */
  getDateDiff(startTime: string, endTime: string, diffType: 'second' | 'minute' | 'hour' | 'day') {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
    startTime = startTime.replace(/-/g, "/");
    endTime = endTime.replace(/-/g, "/");

    //将计算间隔类性字符转换为小写
    var sTime = new Date(startTime); //开始时间
    var eTime = new Date(endTime); //结束时间
    const divNum: number = ({
      "second": 1000,
      "minute": 1000 * 60,
      "hour": 1000 * 3600,
      "day": 1000 * 3600 * 24,
    }[diffType])

    return (eTime.getTime() - sTime.getTime()) / divNum;
  },


  /**
   * 获取当前天的周一到周末的年月日
   * @returns ['2021-10-11', '2021-10-12', '2021-10-13', '2021-10-14', '2021-10-15', '2021-10-16', '20211-0-17']
   */
  weekTime() {
    let dates: Array<string> = [];
    for (var i = 0; i < 7; i++) {
      let week: Date = new Date(time + 24 * 60 * 60 * 1000 * (i - ((Day + 6) % 7)))
      let Ts: string = `${week.getFullYear()}-${PaddingBytes(week.getMonth() + 1)}-${PaddingBytes(week.getDate())}`
      dates.push(Ts)
    }
    return dates;
  },


  /**
   * 获取本周周一年月日
   * @returns 
   */
  monday() {
    return mondayToWeekend().monday
  },

  /**
   * 获取本周日 的时间
   * @returns 
   */
  sunday() {
    return mondayToWeekend().weekend
  },
  /**
   * 获取本月的第一天
   * @returns 
   */
  getCurrentMonthFirst() {
    const date = new Date();
    date.setDate(1);
    const month: number = date.getMonth() + 1,
      day: number = date.getDate();
    return `${date.getFullYear()}-${PaddingBytes(month)}-${PaddingBytes(day)}`
  },
  /**
   * 
   * @returns 获取本月的最后一天
   */
  getCurrentMonthLast() {
    let mydate: Date = new Date(),
      currentMonth = mydate.getMonth(),
      nextMonth = ++currentMonth,
      nextMonthFirstDay: any = new Date(Year, nextMonth, 1),
      oneDay = 1000 * 60 * 60 * 24,
      lastTime = new Date(nextMonthFirstDay - oneDay),
      month = lastTime.getMonth() + 1,
      day = lastTime.getDate(),
      date = new Date(`${Year}-${PaddingBytes(month)}-${PaddingBytes(day)}`);
    return `${date.getFullYear()}-${PaddingBytes(date.getMonth() + 1)}-${date.getDate()}`;
  },

  /**
   * 获取周几
   * @returns string
   */
  getWeekDate(): string {
    const weeks: Array<string> = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    return weeks[Day];
  },

  /**
   * 中国标准时间转化为常规时间
   * @param {ChinaTime} "2022-04-14T03:30:08.000+00:00"
   * @return 2022-04-14 14:45:03
   *
   */
  timeFormatsss(ChinaTime: Date) {
    const getDateTime = new Date(new Date(new Date(ChinaTime)))
    let getMonth = getDateTime.getMonth() + 1,
      getDate = getDateTime.getDate(),
      getHours = getDateTime.getHours(),
      getMinutes = getDateTime.getMinutes(),
      getSeconds = getDateTime.getSeconds();
    return `${ChinaTime.getFullYear()}-${PaddingBytes(getMonth)}-${PaddingBytes(getDate)} ${PaddingBytes(getHours)}:${PaddingBytes(getMinutes)}:${PaddingBytes(getSeconds)}`
  },
  /***
  * 时间戳转时间(yyyy-HH-MM)
  * @param time 时间戳
  * @param format 返回类型
  * @returns {string}
  */
  dateFormat(time: string, format: Boolean = false) {
    const t = new Date(parseInt(time));
    // 日期格式
    // h:i:s
    let gs = format ? 'Y-m-d h:i:s' : 'Y-m-d';
    // format = 'Y-m-d ',
    let year = t.getFullYear(),
      // 由于 getMonth 返回值会比正常月份小 1
      month = t.getMonth() + 1,
      day = t.getDate(),
      hours = t.getHours(),
      minutes = t.getMinutes(),
      seconds = t.getSeconds();
    const hash = {
      'Y': year,
      'm': month <= 9 ? String('0' + month) : month,
      'd': day <= 9 ? '0' + day : day,
      'h': hours <= 9 ? '0' + hours : hours,
      'i': minutes <= 9 ? '0' + minutes : minutes,
      's': seconds <= 9 ? '0' + seconds : seconds
    }

    return gs.replace(/\w/g, o => {
      return hash[o]
    })
  },
  /***
* 秒转天时分秒
* @param second_time
* @returns {string}
*/
  secondTransformation(second_time: number) {
    let time = '' //parseInt(second_time) + "秒";
    if (second_time > 60) {
      let second = second_time % 60;
      let min = second_time / 60;
      time = min + "分" + second + "秒";
      if (min > 60) {
        min = (second_time / 60) % 60;
        let hour = ((second_time / 60) / 60);
        time = hour + "小时" + min + "分" + second + "秒";
        if (hour > 24) {
          hour = (((second_time / 60) / 60) % 24);
          let day = (((second_time / 60) / 60) / 24);
          time = day + "天" + hour + "小时" + min + "分" + second + "秒"
        }
      }
    }
    return time
  },
  /**
 * 倒计时 函数
 * @param item 倒计时时间
 * @param running 正在倒计时中得会执行得函数
 * @param finish 倒计时结束执行得函数
 */
  countDown(item = 60, running: (arg0: NodeJS.Timer, arg1: number) => any, finish: (arg0: NodeJS.Timer, arg1: number) => any) {
    let stop = setInterval(() => {
      if (item <= 0) {
        clearInterval(stop);
        finish instanceof Function && finish(stop, item--);
      } else {
        running instanceof Function && running(stop, item--);
      };
    }, 1000);
  },
  // timeToAccumulate(){
  //   this.dateFormat()
  // }
};


